/*
 * @描述: 
 * @创建者: kilomChou
 * @Date: 2021-04-11 23:43:12
 * @最后编辑: kilomChou
 * @LastEditTime: 2021-10-19 16:59:34
 */

import { _decorator, Component, Node, EventTouch } from 'cc';
import { Proto } from '../../common/data/Proto';
import { XGame } from '../../common/data/XlsxVo';
import { Vec2, ZERO_POS } from '../../common/core/vec2/Vec2';
import { Conn } from '../net/Conn';
const { ccclass, property } = _decorator;

@ccclass('UIRocker')
export class UIRocker extends Component {

    /** 是否控制状态 */
    isCtrled = false;
    /** 摇杆上的点 */
    pointNode!: Node;
    /** 摇杆点移动范围 */
    pointRange = 32;
    /** 上一次发送协议的时间 */
    lastSend = 0
    /** 发送间隔 */
    sendTime:number;

    @property(Node)
    camera: Node

    start() {
        this.sendTime = 1000 / XGame.vo.tps;
        this.pointNode = this.node.children[0];

        this.node.on(Node.EventType.TOUCH_START, this.onCtrl, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onCtrl, this);
        this.node.on(Node.EventType.TOUCH_END, this.onDone, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onDone, this);
    }

    /** 控制摇杆 */
    onCtrl(e: EventTouch) {

        this.isCtrled = true;
        let pos = e.getUILocation();
        let dis = Vec2.dis(this.node.worldPosition, pos);
        //超出的部分
        let extra = dis - this.pointRange;
        if (extra > 0) {
            Vec2.moveTo(pos, this.node.worldPosition, extra, pos);
        }
        this.pointNode.setWorldPosition(pos.x, pos.y, 0);
        let now = Date.now();
        if(Conn.isLocal || (now > this.lastSend + this.sendTime)){
            //发送协议
            let ang = Vec2.ang360(Vec2.angTo(ZERO_POS, this.pointNode.position));
            this.lastSend = now;
            Conn.send(Proto.C2S_CTRL_TURN, { ang });
        }
    }

    /** 结束控制 */
    onDone() {
        this.isCtrled = false
        this.pointNode.setPosition(0, 0);
    }


    update(dt: number) {
    }
}
